<?php

namespace CZTools\Hyperf\library;

use think\Image;

class ImageLib
{
    private static $tump_img_w = 260;
    private static $tump_img_h = 260;
    private static $savePath = './uploads/';
    public $fileurl = '';
    private $imgConfig_size = [
        'compress' => [
            'w' => 720,
            'h' => 520
        ],
        'page_size' => [
            'w' => 720,
            'h' => 520
        ],
    ];

    public function __construct()
    {
    }

    public static function SaveImg_base64(string $base64file = null, string $img_savePath, bool $needtump = false)
    {
        $base64file = $base64file ?? input('file', '');
        if (!empty($data)) {
            $reg = '/data:image\/(\w+?);base64,(.+)$/si';
            if (preg_match($reg, $data, $result)) {
                $img_ext = $result[2]; //图片后缀
                $img_header = $result[1];//图片头信息

                $filename = uniqid((string)mt_rand(0, 9));
                $new_file_name = $filename . '.' . $img_ext;
                $tump_name = $filename . "_t." . $img_ext;

                $save_path = $img_savePath . date('Ymd') . "/";
                if (!is_dir($save_path)) {
                    mkdir($save_path, 0777, true);
                }
                //先保存一份原图,然后其他尺寸的保存直接调用原图路径origin_img_path.
                $origin_res = file_put_contents($save_path . $new_file_name, base64_decode(str_replace($img_header, '', $base64file)));

                if (!$origin_res) {
                    $origin_img_save_flag = false;
                } else {
                    $saveFlag = $new_file_name;
                    $origin_img_path = $save_path . $new_file_name;
                    $image = Image::open($origin_img_path);
                }

                if ($origin_img_save_flag) {
                    $width = self::$tump_img_w;
                    $height = self::$tump_img_h;
                    $image->thumb($width, $height, 1)->save($save_path . $tump_name);
                }
            }

            if ($saveFlag) {
                $saveFlag = rtrim(self::$fileurl, '/') . '/' . ltrim($save_path, './') . $saveFlag;
            }
            return $saveFlag;

        } else {
            return false;
        }
    }
}